package com.kvest.mobile_newspaper.datamodel;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.kvest.mobile_newspaper.core.ArticlesManager;
import com.kvest.mobile_newspaper.utils.StringUtils;

public class ProxyArticle  extends Element
{
	private long date;

    //���� ������ ���� � ������� ��.��.���� ��:��:��
    public ProxyArticle(String id, String name, String date)
    {
        super(id, name);
        this.date = StringUtils.convertDateToLong(date);
    }

    public ProxyArticle(Article article)
    {
        this(article.getId(), article.getName(), article.getDate());
    }
    
    public ProxyArticle(byte[] data) throws IOException
    {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        DataInputStream dis = new DataInputStream(bais);

        try
        {
            id = dis.readUTF();
            name = dis.readUTF();
            
            if (dis.available() > 0)
            {
                date = dis.readLong();
            }
            else
            {
                date = 0;
            }
        }
        finally
        {
            try
            {
                dis.close();
                bais.close();
            }catch(Exception ex){}
        }
    }
    
    public byte[] getBytes()
    {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(result);
        
        try
        {
            //ID
            dos.writeUTF(id);
                    
            //name
            dos.writeUTF(name);
            
            //date
            dos.writeLong(date);
            
            return result.toByteArray();
        }
        catch(IOException ioex)
        {
            return (new byte[]{});
        }
        finally
        {
            try
            {
                dos.close();
                result.close();
            }catch(Exception ex){}
        }
    }

    public long getDate() 
    {
        return date;
    }
    
    public void setWasRead(boolean wasRead)
    {
        if (wasRead)
        {
            ArticlesManager.getManager().setReadArticle(id);
        }
        else
        {
            ArticlesManager.getManager().setUnreadArticle(id);
        }
    }
     
    public boolean wasRead()
    {
        return ArticlesManager.getManager().isReadArticle(id);
    }
    
    public int getUnreadArticlesCount()
    {
        return (wasRead() ? 0 : 1);
    }
    
    public void getAllArticlesId(List<String> ids)
    {
        if (!ids.contains(id))
        {
            ids.add(id);
        }
    }
}
